<template>
  <div id="interMethodOutParamDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" @click="getOutParamList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="同步出参" v-if="detailList.length<=0" @click="syncOutParams"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="复制" @click="copy"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="粘贴" @click="paste"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveBathInterfaceParam"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteInterfaceParam"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="InterfaceParamTableRef" class="mytable-scrollbar" border="inner" align="left" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="detailList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column field="seq" title="序号" width="50" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.seq" type="number"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="outCode" title="外源参数" width="150" :edit-render="{}">
          <template #edit="{ row}">
            <vxe-input v-model="row.outCode" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="code" title="字段名" width="150">
          <template #edit="{ row }">
            <vxe-input v-model="row.code" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="coloumType" title="字段类型" width="100">
          <template #default="{ row }">
            <span>{{ formatCommon(coloumTypeList, row.coloumType) }}</span>
          </template>
          <template #edit="{ row }">
            <vxe-select v-model="row.coloumType" transfer>
              <vxe-option v-for="item in coloumTypeList" :key="item.id" :value="item.code" :label="item.name"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>

        <vxe-column field="common" title="字段说明" width="200">
          <template #edit="{ row }">
            <vxe-input v-model="row.common" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="state" title="是否启用" width="80" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.state" inline-prompt active-text="是" inactive-text="否"></el-switch>
          </template>
        </vxe-column>
        <vxe-column field="isFixed" title="是否固定值" width="100" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.isFixed" inline-prompt active-text="是" inactive-text="否"></el-switch>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { IsEmpty } from '@/utils/common';
import { AppStore } from '@/stores/store';

let store = AppStore();
defineExpose({ initPage });
let methodId = ref(null);
let interfaceDictId = ref(null);
let interfaceParamId = ref(null);
let interfaceType = ref(null);
let detailList: any = reactive([]);
let rloading = ref(false);
let coloumTypeList = reactive([]);
let flag = ref(true);
let interfaceId: any = ref(null);

function initPage(row: any) {
  methodId.value = row.id;
  interfaceDictId.value = row.interfaceDictId;
  interfaceId.value = row.interfaceId;
  getOutParamList();
  //获取字典配置的出参
  getDictItemsList();
}
function getOutParamList() {
  console.log(11111111);
  rloading.value = true;
  detailList.length = 0; //放入数据前清空数据
  const url = '/api/sys/sysInterfaceMethodOutParam/findInterfaceDictOutParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { interfaceId: interfaceId.value, methodId: methodId.value }
    })
    .then((res: any) => {
      console.log(res.data.methodList);
      if (res.data.methodList && res.data.methodList.length > 0) {
        flag.value = true;
        detailList.push(...res.data.methodList);
      } else {
        flag.value = false;
        detailList.push(...res.data.dictList);
      }
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取出参异常', VxeNotifyType.error);
    });
}
//批量获取字典
async function getDictItemsList() {
  coloumTypeList.length = 0;
  let dictTreeTypeCodes: any = ['interfaceColoumType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'interfaceColoumType');
  coloumTypeList.push(...severityType.detailDataList);
}

// 左侧保存
async function saveBathInterfaceParam() {
  if (IsEmpty(methodId.value)) {
    VxeMessage('请选择方法', VxeNotifyType.error);
  } else {
    const sveOrupdateDetail = [] as any[];
    detailList.forEach((e: any) => {
      const iDetail: any = {
        id: flag.value ? e.id : '',
        seq: e.seq,
        interfaceId: interfaceId.value,
        methodId: methodId.value,
        outCode: e.outCode,
        code: e.code,
        common: e.common,
        type: e.type,
        coloumType: e.coloumType,
        state: e.state,
        orgId: e.orgId,
        isFixed: e.isFixed
      };
      sveOrupdateDetail.push(iDetail);
    });
    if (sveOrupdateDetail.length > 0) {
      const url = '/api/sys/sysInterfaceMethodOutParam/saveOrUpdateInterfaceMethodOutParam';
      const obj: any = {};
      obj.datas = sveOrupdateDetail;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          getOutParamList();
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  }
}

// 左侧删除
function deleteInterfaceParam() {
  const sltDetails = (proxy.$refs.InterfaceParamTableRef as any).getCheckboxRecords();
  if (!(sltDetails.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delDetailList = sltDetails.filter((p: any) => !IsEmpty(p.id));
        if (delDetailList.length > 0) {
          const data = { ids: delDetailList.map((p) => p.id) };
          const url = '/api/sys/sysInterfaceMethodOutParam/deleteBatchInterfaceMethodOutParam';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              getOutParamList();
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeDetailList = sltDetails.filter((p: any) => IsEmpty(p.id));
        if (removeDetailList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.InterfaceParamTableRef;
          if ($Xtable) {
            for (const removeRow of removeDetailList) {
              detailList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
/**同步出参 */
function syncOutParams() {
  const url = '/api/sys/getInterfaceDictParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { dictId: interfaceDictId.value, type: '2' }
    })
    .then((res: any) => {
      res.data.forEach(e => {
        const a = {
          interfaceId: interfaceId.value,
          methodId: methodId.value,
          outCode: null,
          code: e.code,
          seq: e.seq,
          coloumType: e.coloumType,
          common: e.common,
          state: e.state
        };
        detailList.push(a);
      });

    })
    .catch((err: any) => {
      VxeMessage('请选择场景', VxeNotifyType.error);
    });
}
/**复制 */
function copy() {
  VxeMessage('已复制到剪贴板', VxeNotifyType.success);
  sessionStorage.setItem('busoutparamcopy', JSON.stringify(detailList));
}
/**粘贴 */
function paste() {
  const a = sessionStorage.getItem('busoutparamcopy');
  const b = JSON.parse(a);
  if (IsEmpty(b) || IsEmpty(a)) {
    VxeMessage('没有要粘贴的数据', VxeNotifyType.warning);
    return;
  }
  if (!methodId.value) {
    VxeMessage('请选择场景', VxeNotifyType.warning);
    return;
  }
  b.forEach(e => {
    e.interfaceId = interfaceId.value;
    e.methodId = methodId.value;
    e.id = null;
  });
  Object.assign(detailList, b);
}
</script>

<style lang="scss" scoped>
#interMethodOutParamDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>